﻿using System;
using System.IO;
using System.Net;

namespace Fadada.FASC.SDK.DotNetCore.Utils
{
    public class DownLoadFile
    {
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="myResponse">HttpWebResponse 返回httpResp</param>
        /// <param name="localPath">本地路径</param>
        /// <param name="localFile">文件名称</param>
        /// <returns></returns>
        public static bool Download(HttpWebResponse myResponse, string localPath, string localFile)
        {
            bool flag = false;
            FileStream writeStream; // 写入本地文件流对象

            //创建目录
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }

            localFile = Path.Combine(localPath + localFile);
            // 判断要下载的文件夹是否存在
            if (File.Exists(localFile))
            {
                File.Delete(localFile);
            }

            writeStream = File.Create(localFile);

            try
            {

                Stream readStream = myResponse.GetResponseStream();// 向服务器请求,获得服务器的回应数据流


                byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次

                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                }

                //关闭流
                writeStream.Close();
                readStream.Close();

                flag = true;        //返回true下载成功
            }
            catch (Exception)
            {
                writeStream.Close();
                flag = false;       //返回false下载失败
            }

            return flag;
        }

       
    }
}